/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.myself.MyReceiveAddressAddActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.GsonFactory;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.ReceiveAddressBaseListAdapter;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.DeliverAddressListReponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.DeliverAddressListReponse.DeliverAddressListModel;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-17 10:32<br/>
 * <p>
 * <p>
 * 提交订单--地址--用户地址列表页面
 * </p>
 */
public class UserAddressActivity extends BaseActivity implements OnItemClickListener {
    /**
     * 无地址提示布局
     */
    private RelativeLayout rllyNoAddressLayout;
    /**
     * 地址列表
     */
    private ListView lyCity;
    /**
     * 地址列表适配器
     */
    private ReceiveAddressBaseListAdapter adapter;

    /**
     * 任务类
     */
    // private DanluTaskProxy danluTaskProxy;

    /**
     * 请求地址类
     */
    private BaseRequest baseRequest = new BaseRequest();

    /**
     * 接收地址类
     */
    private DeliverAddressListReponse addressListReponse;

    /**
     * 传递的地址ID
     */
    private String preAddressId;
    /**
     * 当前选中项
     */
    private int selectedIndex = 0;
    /**
     * 添加收货地址
     */
    private Button AddReceiveBtn;
    /**
     * 收货地址 ID List
     */
    private List<String> orderAddID = new ArrayList<>();
    /**
     * 刷新页面
     */
    private boolean updataFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        getDelegate ().setContentView (R.layout.layout_user_address, R.layout_address.class);
        setContentView(R.layout.activity_user_address);

        initView();
        setViews();
    }

    private void setViews() {
        preAddressId = getIntent().getStringExtra(CommonConst.IntentKey.ADDRESS_ID);
        // 设置token
        if (preAddressId == null) {
            preAddressId = "";
        }
        baseRequest.setToken(agent.getToken());
        // 请求收货地址
        getReceiveAddress();
        AddReceiveBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(UserAddressActivity.this, MyReceiveAddressAddActivity.class);
                intent.putExtra("ORDERADD", "orderAdd");
                startActivityForResult(intent, 200);
            }
        });
    }

    private void getReceiveAddress() {
        agent.getApi()
                .getDeliveryAddressList(baseRequest)
                .compose(OperatorUtils.<DeliverAddressListReponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<DeliverAddressListReponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(DeliverAddressListReponse model) {
                        addressListReponse = model;
                        if (addressListReponse == null || addressListReponse.getDeliverAddressModelList() == null || addressListReponse.getDeliverAddressModelList().size() < 1) {
                            showNoData();
                        } else {
                            showHasData();
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    private void backResult() {
        // 选中的地址模型
        DeliverAddressListModel addressModel = addressListReponse.getDeliverAddressModelList().get(selectedIndex);
        String strModel = GsonFactory.getGson().toJson(addressModel);
        Intent intent = new Intent();
        intent.putExtra(CommonConst.IntentKey.ADDRESS_MODEL, strModel);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 显示无地址提示
     */
    private void showNoData() {
        lyCity.setVisibility(View.GONE);
        rllyNoAddressLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 显示有地址数据
     */
    private void showHasData() {
        lyCity.setVisibility(View.VISIBLE);
        rllyNoAddressLayout.setVisibility(View.GONE);
        adapter = new ReceiveAddressBaseListAdapter(UserAddressActivity.this, addressListReponse);
        lyCity.setAdapter(adapter);
        lyCity.setOnItemClickListener(this);
        // 默认选中之前选中的地址
        if (addressListReponse != null
                && addressListReponse.getDeliverAddressModelList() != null
                && addressListReponse.getDeliverAddressModelList().size() > 0) {
            for (int i = 0; i < addressListReponse.getDeliverAddressModelList().size(); i++) {
                if (updataFlag) {
                    String newid = addressListReponse.getDeliverAddressModelList().get(i).getAddressId();
                    //判断newid是否为新添加的地址ID
                    if (!orderAddID.contains(newid)) {
                        //选中新添加的收货地址ID
                        selectedIndex = i;
                        adapter.setSelectedIndex(i);
                        adapter.notifyDataSetChanged();
                        orderAddID.add(newid);
                    }
                } else {
                    orderAddID.add(addressListReponse.getDeliverAddressModelList().get(i).getAddressId());
                    DeliverAddressListModel addressModel = addressListReponse.getDeliverAddressModelList().get(i);
                    if (addressModel.getAddressId() != null && addressModel.getAddressId().equals(preAddressId)) {
                        selectedIndex = i;
                        adapter.setSelectedIndex(i);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
            updataFlag = false;
        }
    }

    /**
     * 点击切换图片
     */
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
        selectedIndex = index;
        adapter.setSelectedIndex(selectedIndex);
        adapter.notifyDataSetChanged();
        backResult();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 200:
                updataFlag = true;
                // 请求收货地址
                getReceiveAddress();
                break;

            default:
                break;
        }
    }

    private void initView() {
        rllyNoAddressLayout = (RelativeLayout) findViewById(R.id.rllyNoAddressLayout);
        lyCity = (ListView) findViewById(R.id.lyCity);
        AddReceiveBtn = (Button) findViewById(R.id.AddReceiveBtn);
        rllyNoAddressLayout = (RelativeLayout) findViewById(R.id.rllyNoAddressLayout);
    }
}
